import { Injectable } from '@angular/core';
import { Router, Resolve, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { map, take } from 'rxjs/operators';
import { AuthService } from './auth.service';
import { fromPromise } from 'rxjs/internal/observable/fromPromise';

class User {
}

@Injectable()
export class UserInfoResolver implements Resolve<User> {
    constructor(private authSv: AuthService, private router: Router) { }
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<User> {
        const _user = sessionStorage.getItem('user');
        let user;
        switch (_user) {
            case undefined:
            case null:
            case 'undefined':
                return fromPromise(this.authSv.getUser()).pipe(
                    take(1),
                    map((res: any) => {
                        if (res) {
                            sessionStorage.setItem('user', JSON.stringify(res));
                            return res;
                        } else {
                            this.router.navigate(['/login']);
                            return null;
                        }
                    })
                );
            default:
                user = JSON.parse(sessionStorage.getItem('user'));
                return of(user);
        }

    }
}
